﻿using System;
using System.Configuration;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;


namespace Xmobile.BO.UrlRewrite
{
    public class RewriteModule : IHttpHandlerFactory, IRequiresSessionState
    {
        
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url1, string pathTranslated)
        {

            //log.InfoFormat("[RewriteModule] - [GetHandler]:[Start]");
            /*
            if (context.Request.Url.ToString().ToLower().Contains("http://bds.cafef.vn"))
            {
                context.Response.Redirect("http://land.cafef.vn" + context.Request.Path + (context.Request.Url.Query ?? ""));
            }
            //Nếu user vào bằng ĐTDĐ thì đá sang trang m.dantri.com.vn
            if (Libs.IsMobileRedirect(context) || Libs.isMobileBrowser(context))
            {
                context.Response.Redirect("http://m.cafef.vn" + context.Request.Path + (context.Request.Url.Query ?? ""));

                //context.Response.Redirect("http://m.cafef.vn" + context.Request.Url.AbsolutePath);
            }

            if (HttpContext.Current.Request.Url.Query != String.Empty)
            {
                if (context.Request.Url.Query.Length > 0)
                {
                    context.Items["VirtualUrl"] = context.Request.Path + context.Request.Url.Query;
                }
            }
            */
            if (context.Items["VirtualUrl"] == null)
            {
                context.Items["VirtualUrl"] = context.Request.Path;
            }

            string url = context.Request.Url.AbsolutePath;
            //log.InfoFormat("[RewriteModule] - [GetHandler] : [URL] " + url);
            string rewrite = "";

            _301Redirection _301 = new _301Redirection();
            if (!_301.Redirect(url + (context.Request.Url.Query.Length > 0 ? "?" + HttpContext.Current.Request.Url.Query.Replace("?", "") : "")))
            {
                RewriteRules rewriteRules = RewriteRules.GetCurrentRewriteRules();
                rewrite = rewriteRules.GetMatchingRewrite(url);

                if (!string.IsNullOrEmpty(rewrite))
                {
                    context.RewritePath("~" + rewrite);
                }
                else
                {
                    rewrite = context.Request.Path + context.Request.Url.Query;
                }
            }
            string newFilePath = rewrite.IndexOf("?") > 0 ? rewrite.Substring(0, rewrite.IndexOf("?")) : rewrite;

            
            //if (newFilePath.Contains("listaspx.aspx") || newFilePath.Contains("NewsList.aspx") || newFilePath.Contains("WebForm1.aspx")) 
            /*
            if (newFilePath.Contains("listajax.aspx")) 
            {
                //if (CacheController.IsAllowDistributedCached && context.Request.Form.Count == 0)
                if (CacheController.IsAllowDistributedCached)
                {
                    CacheSettings config = CacheSettings.GetCurrentSettings();
                    CacheSettings.PageSetting pageConfig = config.GetPageSetting(rewrite);     
                    /*
                    string dateSearch = Libs.QueryString.DateSearch;
                    string key =
                           string.Format(Constants.CACHE_NAME_FORMAT_HTML_PAGE_CONTENT,
                                         (Libs.QueryString.CategoryID.ToString().Length == 0 || Libs.QueryString.CategoryID == 0 ? pageConfig.Category : Libs.QueryString.CategoryID.ToString()), Libs.QueryString.NewsID, Libs.QueryString.ThreadID, Libs.QueryString.PageIndex, Libs.QueryString.DateSearch);

                    string cacheContent = "";
                    if (Libs.QueryString.PageIndex > 1)
                    {
                        string KeyPageOne = string.Format(Constants.CACHE_NAME_FORMAT_HTML_PAGE_CONTENT,
                                      (Libs.QueryString.CategoryID == 0 || Libs.QueryString.CategoryID.ToString().Length == 0
                                           ? pageConfig.Category
                                           : Libs.QueryString.CategoryID.ToString()), Libs.QueryString.NewsID,
                                      Libs.QueryString.ThreadID,
                                      0, Libs.QueryString.DateSearch);


                        string TimerOld = CacheController.Get<string>(Libs.QueryString.CategoryID.ToString(), String.Format(Constants.CACHE_NAME_LAST_UPDATE, key));
                        string TimerNew = CacheController.Get<string>(Libs.QueryString.CategoryID.ToString(), String.Format(Constants.CACHE_NAME_LAST_UPDATE, KeyPageOne));
                        //Kiem tra thoi gian update cache có trùng nhau ko
                        DateTime dtOld = !String.IsNullOrEmpty(TimerOld)
                                             ? Convert.ToDateTime(TimerOld)
                                             : DateTime.MinValue;
                        DateTime dtNew = !String.IsNullOrEmpty(TimerNew)
                                            ? Convert.ToDateTime(TimerNew)
                                            : DateTime.MinValue;

                        if (dtNew > dtOld)
                        {
                            //Render lại trang cache này
                            return PageParser.GetCompiledPageInstance(newFilePath, context.Server.MapPath(newFilePath), context);
                        }
                    }
                 // tienn dong tai day
                    string cacheContent = "";
                    string key = string.Format(Constants.CACHE_NAME_FORMAT_HTML_PAGE_CONTENT, Libs.QueryString.CategoryID, Libs.QueryString.OS, Libs.QueryString.Sticky, Libs.QueryString.PageIndex);


                    if (config.EnableCache && pageConfig.EnableCache)
                    {
                        if (!string.IsNullOrEmpty(pageConfig.Category))
                        {
                            cacheContent = CacheController.Get<string>(pageConfig.Category, key);
                        }
                        else
                        {
                            cacheContent = CacheController.Get<string>(key);
                        }
                    }
                    if (!string.IsNullOrEmpty(cacheContent))
                    {
                        context.Response.Write(cacheContent);
                        return context.Handler;
                    }
                }

            }
               */
            if (string.IsNullOrEmpty(newFilePath))
                newFilePath = "/blank.aspx";
            //log.InfoFormat("[RewriteModule] - [GetHandler] : [New URL] " + newFilePath);
            return PageParser.GetCompiledPageInstance(newFilePath, context.Server.MapPath(newFilePath), context);
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
        }
    }
}
